package top.lingkang.finalvalidated.handle;

import top.lingkang.finalvalidated.constraints.HasStringValue;
import top.lingkang.finalvalidated.core.FinalValidatorFactory;
import top.lingkang.finalvalidated.error.ValidatedException;
import top.lingkang.finalvalidated.utils.FinalValidatorUtils;

/**
 * @author lingkang
 * created by 2025/11/9 23:35
 */
public class HasStringValueHandle extends ValidHandle {
    private final String errorStr;
    private final HasStringValue hasStringValue;

    public HasStringValueHandle(ValidVal validVal, HasStringValue hasStringValue) {
        super(validVal, hasStringValue);
        this.hasStringValue = hasStringValue;

        if (FinalValidatorUtils.isNotEmpty(hasStringValue.message())) {
            errorStr = hasStringValue.message();
        } else if (FinalValidatorUtils.isNotEmpty(validVal.getTag())) {
            errorStr = FinalValidatorFactory.message.getProperty("HasStringValue")
                    .replace("{attrName}", validVal.getTag());
        } else {
            errorStr = FinalValidatorFactory.message.getProperty("HasStringValue")
                    .replace("{attrName}", validVal.getName());
        }
    }

    @Override
    public void valid(Object target) {
        Object o = validVal.getValGet().get(target);
        if (o == null || notHasStringValue(o)) {
            throw new ValidatedException(errorStr, validVal);
        }
    }

    private boolean notHasStringValue(Object target) {
        try {
            String str = target.toString();
            for (String s : hasStringValue.value()) {
                if (str.equals(s)) {
                    return false;
                }
            }
        } catch (Exception e) {
            return true;
        }
        return true;
    }

    @Override
    public Class<?>[] getGroups() {
        return new Class[0];
    }
}
